package com.luoye_lj.dogcontroller;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.luoye_lj.dogcontroller.dialog.BigTextToast;
import com.luoye_lj.dogcontroller.util.BleGattConnector;

import java.io.IOException;

public class ControlActivity extends AppCompatActivity {
    private BleGattConnector connector;
    private boolean connected = false;

    EditText sendMsgEt;
    Button sendMsgBtn;
    TextView receiveMsgTv;

    Button forwardBtn;
    Button leftBtn;
    Button standBtn;
    Button rightBtn;
    Button backwardBtn;
    Button helloBtn;
    Button danceBtn;
    Button head_upBtn;
    Button lan_yaoBtn;
    Button stretchBtn;
    Button two_handsBtn;
    Button sleep_pBtn;
    Button sleep_wBtn;
    Button shake_qianhouBtn;
    Button shake_zuoyouBtn;
    Button slow_standBtn;
    Button slow_sitDownBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_control);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // 从Intent中获取BluetoothDevice对象
        BluetoothDevice device = getIntent().getParcelableExtra("device");
        if(device==null){
            BigTextToast.makeText(ControlActivity.this, "设备不存在", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        // 连接到设备
        connector = new BleGattConnector(this, device, new BleGattConnector.BleConnectionListener() {
            @Override
            public void onConnected() {
                BigTextToast.makeText(ControlActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                connected = true;
                sendMsgBtn.setEnabled(true);
                sendMsgEt.setEnabled(true);
                receiveMsgTv.setText("连接成功");
            }

            @Override
            public void onDisconnected() {
                //BigTextToast.makeText(ControlActivity.this, "连接断开", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onServicesDiscovered() {
                //BigTextToast.makeText(ControlActivity.this, "服务发现完成", Toast.LENGTH_SHORT).show();
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onDataReceived(byte[] data) {
                //BigTextToast.makeText(ControlActivity.this, "收到数据: " + connector.bytesToHex(data), Toast.LENGTH_SHORT).show();
                receiveMsgTv.setText("收到数据: "+ new String(data) +"(" + connector.bytesToHex(data)+")");
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onError(String errorMessage) {
                BigTextToast.makeText(ControlActivity.this, "错误: " + errorMessage, Toast.LENGTH_SHORT).show();
                receiveMsgTv.setText("错误: " + errorMessage);
            }
        });
        connector.connect();

        sendMsgEt = findViewById(R.id.sendMsgEt);
        sendMsgBtn = findViewById(R.id.sendMsgBtn);
        receiveMsgTv = findViewById(R.id.receiveMsgTv);

        forwardBtn = findViewById(R.id.forwardBtn);
        leftBtn = findViewById(R.id.leftBtn);
        standBtn = findViewById(R.id.standBtn);
        rightBtn = findViewById(R.id.rightBtn);
        backwardBtn = findViewById(R.id.backwardBtn);
        helloBtn = findViewById(R.id.helloBtn);
        danceBtn = findViewById(R.id.danceBtn);
        head_upBtn = findViewById(R.id.head_upBtn);
        lan_yaoBtn = findViewById(R.id.lan_yaoBtn);
        stretchBtn = findViewById(R.id.stretchBtn);
        two_handsBtn = findViewById(R.id.two_handsBtn);
        sleep_pBtn = findViewById(R.id.sleep_pBtn);
        sleep_wBtn = findViewById(R.id.sleep_wBtn);
        shake_qianhouBtn = findViewById(R.id.shake_qianhouBtn);
        shake_zuoyouBtn = findViewById(R.id.shake_zuoyouBtn);
        slow_standBtn = findViewById(R.id.slow_standBtn);
        slow_sitDownBtn = findViewById(R.id.slow_sitDownBtn);

        sendMsgBtn.setOnClickListener(v -> {
            if(!connected){
                BigTextToast.makeText(ControlActivity.this, "设备还没连接", Toast.LENGTH_SHORT).show();
                return;
            }
            String msg = sendMsgEt.getText().toString();
            if(msg.isEmpty()){
                BigTextToast.makeText(ControlActivity.this, "请输入指令", Toast.LENGTH_SHORT).show();
                return;
            }
            byte[] data = hexStringToByteArray(msg);
            connector.writeData(data);
        });
        View.OnClickListener btnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!connected){
                    BigTextToast.makeText(ControlActivity.this, "设备还没连接", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (v.getId() == R.id.forwardBtn) {
                    sendMsgEt.setText("0x32");
                    connector.writeData(new byte[]{0x32});
                } else if (v.getId() == R.id.leftBtn) {
                    sendMsgEt.setText("0x34");
                    connector.writeData(new byte[]{0x34});
                } else if (v.getId() == R.id.standBtn) {
                    sendMsgEt.setText("0x39");
                    connector.writeData(new byte[]{0x39});
                } else if (v.getId() == R.id.rightBtn) {
                    sendMsgEt.setText("0x35");
                    connector.writeData(new byte[]{0x35});
                } else if (v.getId() == R.id.backwardBtn) {
                    sendMsgEt.setText("0x33");
                    connector.writeData(new byte[]{0x33});
                } else if (v.getId() == R.id.helloBtn) {
                    sendMsgEt.setText("0x62");
                    connector.writeData(new byte[]{0x62});
                } else if (v.getId() == R.id.danceBtn) {
                    sendMsgEt.setText("0x38");
                    connector.writeData(new byte[]{0x38});
                } else if (v.getId() == R.id.head_upBtn) {
                    sendMsgEt.setText("0x64");
                    connector.writeData(new byte[]{0x64});
                } else if (v.getId() == R.id.lan_yaoBtn) {
                    sendMsgEt.setText("0x63");
                    connector.writeData(new byte[]{0x63});
                } else if (v.getId() == R.id.stretchBtn) {
                    sendMsgEt.setText("0x61");
                    connector.writeData(new byte[]{0x61});
                } else if (v.getId() == R.id.two_handsBtn) {
                    sendMsgEt.setText("0x43");
                    connector.writeData(new byte[]{0x43});
                } else if (v.getId() == R.id.sleep_pBtn) {
                    sendMsgEt.setText("0x65");
                    connector.writeData(new byte[]{0x65});
                } else if (v.getId() == R.id.sleep_wBtn) {
                    sendMsgEt.setText("0x66");
                    connector.writeData(new byte[]{0x66});
                } else if (v.getId() == R.id.shake_qianhouBtn) {
                    sendMsgEt.setText("0x36");
                    connector.writeData(new byte[]{0x36});
                } else if (v.getId() == R.id.shake_zuoyouBtn) {
                    sendMsgEt.setText("0x37");
                    connector.writeData(new byte[]{0x37});
                } else if (v.getId() == R.id.slow_standBtn) {
                    sendMsgEt.setText("0x31");
                    connector.writeData(new byte[]{0x31});
                } else if (v.getId() == R.id.slow_sitDownBtn) {
                    sendMsgEt.setText("0x42");
                    connector.writeData(new byte[]{0x42});
                }
            }
        };
        forwardBtn.setOnClickListener(btnClickListener);
        leftBtn.setOnClickListener(btnClickListener);
        standBtn.setOnClickListener(btnClickListener);
        rightBtn.setOnClickListener(btnClickListener);
        backwardBtn.setOnClickListener(btnClickListener);
        helloBtn.setOnClickListener(btnClickListener);
        danceBtn.setOnClickListener(btnClickListener);
        head_upBtn.setOnClickListener(btnClickListener);
        lan_yaoBtn.setOnClickListener(btnClickListener);
        stretchBtn.setOnClickListener(btnClickListener);
        two_handsBtn.setOnClickListener(btnClickListener);
        sleep_pBtn.setOnClickListener(btnClickListener);
        sleep_wBtn.setOnClickListener(btnClickListener);
        shake_qianhouBtn.setOnClickListener(btnClickListener);
        shake_zuoyouBtn.setOnClickListener(btnClickListener);
        slow_standBtn.setOnClickListener(btnClickListener);
        slow_sitDownBtn.setOnClickListener(btnClickListener);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(connector!=null){
            connector.disconnect();
        }
        connector = null;
    }

    private static byte[] hexStringToByteArray(String s) {
        s = s.replace("0x", "");
        if (s == null || s.length() % 2 != 0) {
            throw new IllegalArgumentException("输入字符串长度必须为偶数");
        }
        byte[] data = new byte[s.length() / 2];
        for (int i = 0; i < s.length(); i += 2) {
            int highNibble = Character.digit(s.charAt(i), 16);
            int lowNibble = Character.digit(s.charAt(i + 1), 16);
            if (highNibble == -1 || lowNibble == -1) {
                throw new IllegalArgumentException("包含非16进制字符");
            }
            data[i / 2] = (byte) ((highNibble << 4) + lowNibble);
        }
        return data;
    }
}